package com.supostacks.xuetangerp.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.rpc.server.dto.BaseDto;
import com.supostacks.rpc.server.dto.UserDto;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserController extends BaseController {
    @Override
    public BaseDto buildData(JSONObject json) {
        return JSONObject.toJavaObject(json, UserDto.class);
    }

    @Override
    public BaseDto takeBaseDto() {
        return new UserDto();
    }

    @RequestMapping("/login")
    public SaResult login(@RequestParam("code") String code) {
        String openid = getOpenid(code);
        if (StringUtils.hasText(openid)) {
            SaResult saResult = selectById(openid);
            if (saResult.getCode() == 200) {
                Map data = (Map) saResult.getData();
                if (data != null) {
                    StpUtil.login(data.get("id"));
                    SaResult insert = SaResult.ok("登录成功").setData(data);
                    fillUser(insert);
                    return insert;
                } else {
                    UserDto userDto = UserDto.builder().id(openid)
                            .createTime(new Date())
                            .level("普通用户")
                            .isAdmin(false)
                            .nickname("微信用户" + openid.substring(0, 5)).build();
                    JSONObject parsed = JSONObject.parseObject(JSONObject.toJSONString(userDto));
                    SaResult insert = insert(parsed);
                    if (insert.getCode() == 200) {
                        insert.setData(userDto);
                        StpUtil.login(openid);
                    }
                    fillUser(insert);

                    return insert;
                }
            }
        }
        return SaResult.error("登录失败");
    }

    public void fillUser(SaResult insert) {
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String tokenValue = tokenInfo.getTokenValue();
        String tokenName = tokenInfo.getTokenName();

        JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(insert.getData()));
        result.put("tokenName", tokenName);
        result.put("tokenValue", tokenValue);
        insert.setData(result);
    }

    public String getOpenid(String code) {
        Map<String, String> getenv = System.getenv();
        HttpResponse execute = HttpUtil
                .createGet("https://api.weixin.qq.com/sns/jscode2session")
                .form("js_code", code)
                .form("appid", getenv.get("WEIXIN_APPID"))
                .form("secret", getenv.get("WEIXIN_SECRET"))
                .form("grant_type", "authorization_code")
                .execute();

        if (execute.getStatus() == 200) {
            JSONObject json = JSONObject.parseObject(execute.body());
            return json.getString("openid");
        }

        return null;
    }

    @RequestMapping("/register")
    public SaResult register(JSONObject json) {
        return insert(json);
    }

    @RequestMapping("/logout")
    public SaResult logout(@RequestParam("id") String id) {
        try {
            StpUtil.logout(id);
            return SaResult.ok("退出成功");
        } catch (Exception e) {
            return SaResult.error("退出失败");
        }
    }
}
